package com.lsy.seckill.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lsy.seckill.pojo.User;
import com.lsy.seckill.service.UserService;
import com.lsy.seckill.mapper.UserMapper;
import com.lsy.seckill.util.CookieUtil;
import com.lsy.seckill.util.MD5Util;
import com.lsy.seckill.util.UUIDUtil;
import com.lsy.seckill.vo.LoginVo;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
* @author 19040
* @description 针对表【seckill_user】的数据库操作Service实现
* @createDate 2024-09-13 15:04:44
*/
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
    implements UserService {
    @Resource
    private UserMapper userMapper;
    @Resource
    private RedisTemplate redisTemplate;

    //根据Cookie-ticket 获取用户
    @Override
    public User getUserByCookie(String userTicket, HttpServletRequest request, HttpServletResponse response) {

        if (!StringUtils.hasText(userTicket)) {
            return null;
        }

        //根据userTicket到Redis获取user
        User user = (User) redisTemplate.opsForValue().get("user:" + userTicket);
        //如果用户不为null, 就重新设置cookie,刷新, 这里是根据你的业务需要来的
        if (user != null) {
            CookieUtil.setCookie(request, response, "userTicket", userTicket);
        }

        return user;
    }

    public Boolean checkLogin(LoginVo loginVo, HttpServletRequest request, HttpServletResponse response){
        Long mobile = loginVo.getMobile();
        String password = loginVo.getPassword();
       //从数据库中取出user
        User user = userMapper.selectById(mobile);
        //判断是否登录成功
        if (user==null){
            return false;
        }
        if (!MD5Util.midPassToDBPass(password,user.getSlat()).equals(user.getPassword())){
            return false;
        }
        String uuid = UUIDUtil.uuid();
        //将登录成功的用户生成唯一的票据值，存在Cookie中，
        CookieUtil.setCookie(request,response,"ticket", uuid);
//        再将用户以票据值为key，用户为值存在Redis中以便后续使用时不用去DB
        redisTemplate.opsForValue().set("user:"+uuid,user);
        return true;
    }
}




